package com.pogita.cleancode.testprotectionjava.services;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pogita.cleancode.testprotectionjava.model.Result;
import lombok.NoArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;


@Service
@NoArgsConstructor
public class PaymentService {
    private final MediaType jsonMediaType = MediaType.get("application/json;charset=utf-8");

    private final OkHttpClient client = new OkHttpClient();

    public Result<String> pay(@RequestParam String username, long money, String sign, long timestamp) {
        JSONObject jsonObject = buildJsonParam(username, money, sign, timestamp);

        Request request = buildRequest(jsonObject);
        try (Response response = client.newCall(request).execute()) {
            return JSON.parseObject(response.body().string(), Result.class);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
    }

    private Request buildRequest(JSONObject jsonObject) {
        RequestBody body = RequestBody.create(jsonObject.toJSONString(), jsonMediaType);
        return new Request.Builder()
                .url("http://localhost/payment-system/pay")
                .post(body)
                .build();
    }

    private JSONObject buildJsonParam(String username, long money, String sign, long timestamp) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", username);
        jsonObject.put("money", money);
        jsonObject.put("sign", sign);
        jsonObject.put("timestamp", timestamp);
        return jsonObject;
    }
}